import { useAntdTable } from 'ahooks';
import { Button, Card, Descriptions, Divider, message, Row, Tag, Typography } from 'antd';
import React, { useState } from 'react';
import SlickTable from '@/components/SlickTable';
import request from '@/utils/request';
import Space from '@/components/Space';
import useModal from '@/hooks/UseModal';
import AddUserModal from './AddUserModal';
import AddTenantModal from './AddTenantModal';
import { isMultiTenant } from '@/utils/user';
import { EMPTY_DATA } from '@/utils/page';

const { Item } = Descriptions;
const { Text } = Typography;

function fetchTenants({ current, pageSize, userId }) {
  if (!isMultiTenant()) {
    return EMPTY_DATA;
  }
  return request.post('/tenant/pageTenantsWithUserId', {
    data: {
      current,
      pageSize,
      userId,
    },
  });
}

function UserDetail({ record, goToStep }) {
  const { userId } = record;
  const {
    tableProps: { loading, ...restTableProps },
    refresh,
  } = useAntdTable(query => fetchTenants({ ...query, userId }), {
    defaultPageSize: 10,
  });

  const { visible, hideModal, showModal } = useModal();
  const [mask, setMask] = useState(false);

  const removeRelation = tenantId => {
    setMask(true);
    request
      .post(`/tenant/removeRelation?userId=${userId}&tenantId=${tenantId}`)
      .then(() => {
        message.success('取消成功');
        refresh();
      })
      .finally(() => setMask(false));
  };

  const setDefaultTenant = tenantId => {
    setMask(true);
    request
      .post(`/tenant/setDefaultTenant?userId=${userId}&tenantId=${tenantId}`)
      .then(() => {
        message.success('设置成功');
        refresh();
      })
      .finally(() => setMask(false));
  };

  const columns = [
    {
      title: '租户ID',
      dataIndex: 'tenantId',
    },
    {
      title: '租户名称',
      dataIndex: 'tenantName',
    },
    {
      title: '租户编码',
      dataIndex: 'tenantCode',
    },
    {
      title: 'HTTP数据源URL前缀',
      dataIndex: 'httpDataSourceUrlPrefix',
    },
    {
      title: '是否默认租户',
      dataIndex: 'defaultTenant',
      render: defaultTenant => defaultTenant && <Tag color="#5bc0de">默认租户</Tag>,
    },
    {
      title: '操作',
      width: 300,
      render: (_, record) => (
        <Space divider="vertical">
          {!record.defaultTenant && (
            <a onClick={() => setDefaultTenant(record.tenantId)}>设置为默认租户</a>
          )}
          <a onClick={() => removeRelation(record.tenantId)}>取消关联</a>
        </Space>
      ),
    },
  ];

  return (
    <Card
      title="用户详情"
      bodyStyle={{ padding: '16px 16px 128px 32px' }}
      extra={
        <Button type="primary" onClick={() => goToStep(1)}>
          返回
        </Button>
      }
    >
      <div className="ant-detail-title">基本信息</div>
      <Descriptions column={4}>
        <Item label="用户ID">{record.userId}</Item>
        <Item label="用户名">{record.username}</Item>
      </Descriptions>
      {isMultiTenant() && (
        <>
          <Divider />
          <Row className="margin-bottom" type="flex" justify="space-between" align="middle">
            <div className="ant-detail-title" style={{ marginBottom: 0 }}>
              租户列表
            </div>
            <Button type="primary" icon="plus" onClick={showModal}>
              添加租户
            </Button>
          </Row>
          <SlickTable
            loading={mask || loading}
            rowKey="userId"
            columns={columns}
            {...restTableProps}
          />
          {visible && (
            <AddTenantModal
              userId={userId}
              onCancel={hideModal}
              onOk={() => {
                hideModal();
                refresh();
              }}
            />
          )}
        </>
      )}
    </Card>
  );
}

export default UserDetail;
